﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace cn.Util
{
    public class CodeTime
    {
        /// <summary>
        /// 执行这个方法
        /// </summary>
        /// <param name="ac"></param>
        /// <param name="preheat">预热执行的次数，这个时间不计入执行时间</param>
        /// <param name="title">代码说明，将在控制台输出时带入,如果不输入将不在控制输出</param>
        /// <returns>执行毫秒数</returns>
        public static double RunTime(Action ac, int preheat = 0,string title="")
        {
            //预热代码
            for (int i = 0; i < preheat; i++)
            {
                ac();
            }

            //控制台输出
            if (string.IsNullOrEmpty(title) == false && preheat!=0)
            {
                Console.WriteLine("代码“" + title + "” 预热结束，开始执行");
            }

            CodeTime ct = new CodeTime();
            ct.Open();
            ac();
            double overtime= ct.Close();

            //控制台输出
            if (string.IsNullOrEmpty(title) == false)
            {
                Console.WriteLine("代码“" + title + "” 执行时间为：" + overtime + " 毫秒");
            }

            return overtime;
        }


        DateTime openTime;

        public void Open()
        {
            openTime = DateTime.Now;
        }



        /// <summary>
        /// 执行结束 
        /// </summary>
        /// <returns>执行毫秒数</returns>
        public double Close()
        {
            return (DateTime.Now - openTime).TotalMilliseconds;
        }

    }
}
